/**
 * 战技指标表迁移脚本 - 移除category_name列
 * 将category_name的值迁移到indicator_chinese字段
 */

const { pool } = require('../config/db');

async function migrateRemoveCategoryName() {
  const connection = await pool.getConnection();
  
  try {
    console.log('开始迁移 weapon_specifications 表（移除category_name列）...');
    
    await connection.beginTransaction();
    
    // 1. 检查是否存在category_name列
    const [columns] = await connection.query(`
      SHOW COLUMNS FROM weapon_specifications LIKE 'category_name'
    `);
    
    if (columns.length === 0) {
      console.log('✓ 表结构已是最新版本，无需迁移');
      await connection.commit();
      return;
    }
    
    // 2. 备份原有数据
    console.log('- 备份原有数据...');
    const [oldData] = await connection.query('SELECT * FROM weapon_specifications');
    console.log(`  备份了 ${oldData.length} 条记录`);
    
    // 3. 将category_name的值迁移到indicator_chinese
    console.log('- 迁移category_name到indicator_chinese...');
    await connection.query(`
      UPDATE weapon_specifications 
      SET indicator_chinese = category_name 
      WHERE node_type = 'category' AND category_name IS NOT NULL AND category_name != ''
    `);
    
    // 4. 删除category_name列
    console.log('- 删除category_name列...');
    await connection.query(`
      ALTER TABLE weapon_specifications DROP COLUMN category_name
    `);
    
    await connection.commit();
    console.log('✅ 迁移完成！');
    console.log('说明：');
    console.log('  - category_name列已删除');
    console.log('  - 分类节点的名称已迁移到indicator_chinese字段');
    console.log('  - 统一使用indicator_chinese和indicator_english字段存储名称');
    
  } catch (error) {
    await connection.rollback();
    console.error('❌ 迁移失败:', error.message);
    throw error;
  } finally {
    connection.release();
  }
}

// 执行迁移
if (require.main === module) {
  migrateRemoveCategoryName()
    .then(() => {
      console.log('迁移脚本执行完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('迁移脚本执行失败:', error);
      process.exit(1);
    });
}

module.exports = { migrateRemoveCategoryName };

